<template>
  <div class="ai-container">
    <!-- 头部导航 -->
    <div class="header">
      <div class="back"><el-icon><ArrowLeft /></el-icon></div>
      <div class="title">快速问诊</div>
      <div class="header-actions">
        <el-tooltip content="在线聊天" placement="bottom">
          <div class="chat-btn" @click="toggleChat">
            <el-icon><ChatDotRound /></el-icon>
            <div class="connection-status" :class="{ 'connected': wsState }"></div>
          </div>
        </el-tooltip>
        <div class="notification"><el-icon><Bell /></el-icon></div>
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-content" ref="chatContainer">
      <el-timeline>
        <!-- AI初始消息 -->
        <el-timeline-item>
          <div class="message doctor-message">
            <div class="avatar">
              <img :src="doctorAvatar" alt="医生头像"/>
            </div>
            <div class="message-content">
              你好，请详细描述您的病情，我们将会安排适合的医生为您服务
            </div>
          </div>
        </el-timeline-item>

        <!-- 快速选择标签 -->
        <el-timeline-item>
          <div class="quick-tags">
            <div class="hint-text">您也可以点击标签快速回答：</div>
            <div class="tags-container">
              <el-tag
                v-for="tag in quickTags"
                :key="tag"
                @click="selectTag(tag)"
                effect="plain"
                class="tag-item">
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </el-timeline-item>

        <!-- 聊天记录 -->
        <el-timeline-item
          v-for="(message, index) in chatHistory"
          :key="index">
          <div :class="['message', message.role === 'user' ? 'user-message' : 'doctor-message']">
            <div class="avatar" v-if="message.role !== 'user'">
              <img :src="doctorAvatar" alt="医生头像"/>
            </div>
            <div class="message-content">
              <!-- 普通消息文本 -->
              <div class="message-text">{{ message.content }}</div>
              
              <!-- 医生列表 -->
              <div v-if="message.role === 'assistant' && hasDoctorList(message.content)" class="doctors-list">
                <div class="list-title">推荐医生列表</div>
                <div v-for="(doctor, idx) in extractDoctors(message.content)" :key="idx" class="doctor-card">
                  <div class="doctor-info">
                    <div class="doctor-main">
                      <div class="doctor-avatar">
                        <img :src="doctorAvatar" alt="医生头像"/>
                      </div>
                      <div class="doctor-details">
                        <div class="doctor-name">{{ doctor.name }}医生</div>
                        <div class="doctor-specialty">{{ doctor.department }}</div>
                      </div>
                    </div>
                    <div class="doctor-price">
                      <div class="price-info">
                        <span class="price-label">挂号费：</span>
                        <span class="price-amount">¥{{ doctor.price }}</span>
                      </div>
                      <el-button type="primary" class="consult-btn" @click="startConsult(doctor)">
                        挂号
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="avatar" v-if="message.role === 'user'">
              <img :src="userAvatar" alt="用户头像"/>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 底部输入区域 -->
    <div class="input-area">
      <div class="input-box">
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="1"
          placeholder="描述越细致，推荐越准确，至少2个字"
          @keyup.enter.native="sendMessage"
        />
        <div class="action-buttons">
          <el-icon class="action-icon"><Microphone /></el-icon>
          <el-icon class="action-icon"><PictureFilled /></el-icon>
          <el-icon class="action-icon" @click="startVideoCall" title="视频通话"><VideoCameraFilled /></el-icon>
        </div>
      </div>
      <el-button type="primary" class="send-btn" @click="sendMessage" :loading="loading">
        发送
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ArrowLeft, Bell, Microphone, PictureFilled, VideoCameraFilled, ChatDotRound } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { selectDiseaseByBodyName } from "@/api/body/body.js"
import { useRoute } from 'vue-router'
import { userInfo } from "@/api/system/user.js"

const route = useRoute()
const chatHistory = ref([])
const userInput = ref('')
const loading = ref(false)
const chatContainer = ref(null)
let eventSource = null

// WebSocket相关状态
const wsState = ref(false)
const isInConsultation = ref(false)
const websocket = ref(null)
const wsAddress = ref('ws://localhost:1212')
let userId = 1

// 初始化用户信息
const userName = ref('')

// 使用在线图片或者base64图片作为默认头像
const doctorAvatar = ''
const userAvatar = ''

// 快速选择标签
const quickTags = ref([])

// 获取疾病标签
const fetchDiseaseTags = async () => {
  try {
    const bodyName = route.query.bodyName
    if (bodyName) {
      const res = await selectDiseaseByBodyName(bodyName)
      if (res.data && res.data.diseaseName) {
        // 将逗号分隔的字符串转换为数组
        quickTags.value = res.data.diseaseName.split(',')
      }
    }
  } catch (error) {
    console.error('获取疾病标签失败:', error)
    ElMessage.error('获取疾病标签失败')
  }
}

// 选择快速标签
const selectTag = (tag) => {
  userInput.value = tag
  sendMessage()
}

// WebSocket连接函数
const connectWebsocket = () => {
  if (websocket.value?.readyState === WebSocket.OPEN) {
    ElMessage.warning("WebSocket已连接")
    return
  }

  try {
    websocket.value = new WebSocket(wsAddress.value)

    websocket.value.onopen = () => {
      wsState.value = true
      websocket.value.send(JSON.stringify({
        code: "10001",
        nickname: userName.value
      }))
      joinGroup()
    }

    websocket.value.onmessage = (e) => {
      const data = JSON.parse(e.data)
      // 将WebSocket消息添加到聊天历史
      chatHistory.value.push({
        role: data.nickname === userName.value ? 'user' : 'assistant',
        content: data.content || data.message
      })
      scrollToBottom()
    }

    websocket.value.onerror = (e) => {
      console.error("WebSocket错误:", e)
      ElMessage.error("WebSocket连接错误")
    }
    
    websocket.value.onclose = () => {
      wsState.value = false
      ElMessage.info("WebSocket连接已关闭")
    }

  } catch (error) {
    console.error("连接失败:", error)
    ElMessage.error("连接服务器失败")
  }
}

// 加入群组
const joinGroup = () => {
  if (websocket.value?.readyState === WebSocket.OPEN) {
    websocket.value.send(JSON.stringify({
      code: "10003",
      nickname: userName.value
    }))
  }
}

// 生成房间ID
const generateRoomId = () => {
  return '1235115'
}

// 获取或生成房间号
const getOrGenerateRoomId = () => {
  const urlParams = new URLSearchParams(window.location.search)
  let roomId = urlParams.get('roomId')

  if (!roomId) {
    roomId = generateRoomId()
    const newUrl = new URL(window.location.href)
    newUrl.searchParams.set('roomId', roomId)
    window.location.replace(newUrl.toString())
    return roomId
  }

  return roomId
}

// 开始视频通话
const startVideoCall = () => {
  const roomId = getOrGenerateRoomId()
  const currentHost = window.location.hostname
  const isLocal = currentHost === 'localhost' || currentHost === '127.0.0.1'
  const targetHost = isLocal ? 'localhost' : currentHost

  const url = new URL(`https://${targetHost}:8087/toMeeting`)
  url.searchParams.append('userId', userName.value)
  url.searchParams.append('roomId', roomId)

  window.location.href = url.toString()
}

// 检查消息是否包含医生列表
const hasDoctorList = (content) => {
  console.log('检查是否包含医生列表，内容:', content);
  
  // 检查是否包含医生推荐的关键信息
  const hasDoctor = content.includes('症状');
  const hasFee = content.includes('元');
                           content.includes('这里有一些') ||
                           content.includes('为您推荐') ||
                           /\d+\.\s*[^，。]+医生/.test(content);
  
  const result = hasDoctor && hasFee;
  console.log('检查结果:', { hasDoctor, hasFee, result });
  return result;
}

// 提取医生信息
const extractDoctors = (content) => {
  const doctors = [];
  console.log('正在解析的内容:', content);

  // 更新主要正则表达式以匹配当前格式
  const mainRegex = /(\d+)\.\s*([^：]+)医生：\s*(?:专长于|擅长)?([^，。]+)[，。]\s*挂号费(?:用)?为(\d+)元/g;
  let match;

  while ((match = mainRegex.exec(content)) !== null) {
    console.log('匹配到的医生信息:', match);
    doctors.push({
      name: match[2].trim(),
      title: '专家医师',
      department: '专科',
      specialty: match[3] ? match[3].trim() : '',
      price: parseInt(match[4])
    });
  }

  // 如果没有匹配到任何医生，尝试使用备用正则表达式
  if (doctors.length === 0) {
    const backupRegex = /([^，。\d]+)医生[：，。]?\s*(?:专长于|擅长)?([^，。]+)[，。]\s*挂号费(?:用)?为(\d+)元/g;
    while ((match = backupRegex.exec(content)) !== null) {
      console.log('使用备用正则匹配到的医生信息:', match);
      doctors.push({
        name: match[1].trim(),
        title: '专家医师',
        department: '专科',
        specialty: match[2] ? match[2].trim() : '',
        price: parseInt(match[3])
      });
    }
  }

  console.log('提取到的医生列表：', doctors);
  return doctors;
}

// 开始咨询
const startConsult = async (doctor) => {
  // 检查医生信息是否完整
  if (!doctor || !doctor.name) {
    ElMessage.error('医生信息不完整，请重试')
    return
  }

  // 检查患者姓名是否存在
  if (!userName.value) {
    ElMessage({
      type: 'warning',
      message: '请先设置您的姓名',
      showClose: true,
      duration: 3000
    })
    // 提示用户输入姓名
    try {
      const name = await ElMessageBox.prompt('请输入您的姓名', '设置姓名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\u4e00-\u9fa5]{2,6}$/,
        inputErrorMessage: '姓名必须是2-6个汉字'
      });
      
      if (name.value) {
        userName.value = name.value;
        // 保存用户名到 localStorage，确保刷新页面后仍然可用
        localStorage.setItem('patientName', name.value);
        // 设置姓名后继续预约流程
        await sendRegistrationMessage(doctor);
      }
    } catch (error) {
      console.log('用户取消输入姓名');
    }
    return;
  }

  // 直接调用预约消息发送函数
  await sendRegistrationMessage(doctor);
}

// 新增：发送预约消息的函数
const sendRegistrationMessage = async (doctor) => {
  try {
    // 保存医生信息到临时变量
    const currentDoctor = {
      name: doctor.name,
      price: doctor.price
    };

    // 设置预约消息
    userInput.value = `我要预约${doctor.name}医生`;

    // 发送预约消息
    await sendMessage(currentDoctor);
  } catch (error) {
    console.error('发送预约消息失败:', error);
    ElMessage.error('预约失败，请重试');
  }
}

// 修改 sendMessage 函数
const sendMessage = async (registrationDoctor = null) => {
  if (!userInput.value.trim()) return
  if (userInput.value.length < 2) {
    ElMessage.warning('请至少输入2个字')
    return
  }

  // 如果已经在实时咨询中，直接发送消息到WebSocket
  if (isInConsultation.value && websocket.value?.readyState === WebSocket.OPEN) {
    // 获取医生名称
    const doctorName = chatHistory.value.find(msg => msg.role === 'assistant' && msg.doctorName)?.doctorName;
    console.log('当前医生名称:', doctorName);

    const message = {
      code: "10002",
      nickname: userName.value,
      role: "patient",
      target: doctorName,
      content: userInput.value,
      type: "2"  // 添加type字段
    };

    if (!message.target) {
      console.error('未找到目标医生名称，聊天记录:', chatHistory.value);
      ElMessage.warning('无法确定目标医生，请重新连接');
      return;
    }

    try {
      console.log('发送WebSocket消息:', message);
      websocket.value.send(JSON.stringify(message));
      userInput.value = '';
    } catch (error) {
      console.error('发送消息失败:', error);
      ElMessage.error('发送消息失败，请重试');
    }
    return;
  }

  // 以下是AI对话的逻辑
  if (eventSource) {
    eventSource.close()
  }

  // 添加用户消息
  chatHistory.value.push({
    role: 'user',
    content: userInput.value
  })

  loading.value = true

  // 构建请求参数
  const requestParams = new URLSearchParams({
    message: userInput.value,
    type: userInput.value.includes('预约') ? 'registration' : 'symptom'
  })

  // 创建新的 SSE 连接
  eventSource = new EventSource(`http://localhost:9209/ai/generateStreamAsString?${requestParams.toString()}`)

  // 准备AI回复
  const aiMessageIndex = chatHistory.value.push({
    role: 'assistant',
    content: ''
  }) - 1

  let fullResponse = '';

  eventSource.onmessage = async (event) => {
    if (event.data === '[complete]') {
      eventSource.close()
      loading.value = false

      // 检查是否包含预约成功的关键词
      const isRegistrationSuccess = fullResponse.includes('挂号编码是') ||
                                  fullResponse.includes('挂号号码是') ||
                                  fullResponse.includes('挂号序号是') ||
                                  fullResponse.includes('预约成功') ||
                                  fullResponse.includes('已为您成功预约') ||
                                  fullResponse.includes('成功预约') ||
                                  fullResponse.includes('我们之前已经为您安排了') ||
                                  /我们之前已经为您安排了.*医生的预约/.test(fullResponse) ||
                                  /您已经成功预约了.*医生/.test(fullResponse) ||
                                  /您选择了.*医生进行预约/.test(fullResponse);

      // 如果是预约成功且有医生信息，或者是重复预约的情况
      if (isRegistrationSuccess) {
        try {
          // 提取挂号编码
          const registrationNumber = fullResponse.match(/\d{12}/)?.[0] || '';
          console.log('提取到的挂号编码:', registrationNumber);

          // 如果是重复预约，从回复中提取医生信息
          if (!registrationDoctor) {
            // 修改正则表达式以匹配更多情况
            const doctorMatch = fullResponse.match(/为您安排了(李龙飞|张义)医生/) ||
                              fullResponse.match(/已经为您安排了(李龙飞|张义)医生/) ||
                              fullResponse.match(/预约了(李龙飞|张义)医生/);

            if (doctorMatch) {
              const doctorName = doctorMatch[1];
              console.log('从回复中提取到的医生姓名:', doctorName);

              // 设置默认挂号费（根据实际情况调整）
              registrationDoctor = {
                name: doctorName,
                price: 50  // 默认挂号费
              };

              // 尝试从聊天记录中找到更准确的挂号费
              const doctorInfo = chatHistory.value
                .slice()
                .reverse()
                .find(msg => {
                  if (msg.role === 'assistant') {
                    const doctors = extractDoctors(msg.content);
                    return doctors.some(doc => doc.name === doctorName);
                  }
                  return false;
                });

              if (doctorInfo) {
                const doctors = extractDoctors(doctorInfo.content);
                const doctor = doctors.find(doc => doc.name === doctorName);
                if (doctor?.price) {
                  registrationDoctor.price = doctor.price;
                }
              }

              console.log('找到的医生信息:', registrationDoctor);
            }
          }

          if (registrationDoctor?.price) {
            const result = await ElMessageBox.confirm(
              `预约成功！您的挂号编码是${registrationNumber}，点击确定进行支付。`,
              '预约成功',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success',
                closeOnClickModal: false,
                closeOnPressEscape: false,
                showClose: false
              }
            );

            if (result === 'confirm') {
              // 跳转到支付页面，带上挂号费参数
              const paymentUrl = "http://localhost:8080/pay/alipay/pay/"+registrationDoctor.price+"/"+registrationNumber;
              console.log('准备跳转到支付页面:', paymentUrl);
              
              // 打开支付页面并添加自动关闭脚本
              const paymentWindow = window.open(paymentUrl, '_blank');
              
              // 在支付页面添加检查支付状态的脚本
              if (paymentWindow) {
                try {
                  paymentWindow.onload = function() {
                    const script = paymentWindow.document.createElement('script');
                    script.textContent = `
                      // 检查支付状态的函数
                      async function checkPaymentStatus() {
                        try {
                          const response = await fetch('http://localhost:8080/pay/alipay/status/${registrationNumber}');
                          const data = await response.json();
                          
                          if (data.status === 'SUCCESS') {
                            // 支付成功，关闭窗口
                            window.close();
                            return true;
                          }
                          return false;
                        } catch (error) {
                          console.error('检查支付状态时出错:', error);
                          return false;
                        }
                      }

                      // 每3秒检查一次支付状态
                      const checkInterval = setInterval(async () => {
                        const isSuccess = await checkPaymentStatus();
                        if (isSuccess) {
                          clearInterval(checkInterval);
                        }
                      }, 3000);

                      // 60秒后停止检查
                      setTimeout(() => {
                        clearInterval(checkInterval);
                      }, 60000);
                    `;
                    paymentWindow.document.body.appendChild(script);
                  };
                } catch (error) {
                  console.error('添加支付检查脚本失败:', error);
                }
              }

              // 在主页面也检查支付状态
              const checkMainPageStatus = async () => {
                try {
                  const response = await fetch(`http://localhost:8080/pay/alipay/status/${registrationNumber}`);
                  const data = await response.json();
                  
                  if (data.status === 'SUCCESS') {
                    // 支付成功
                    ElMessage.success('支付成功！');
                    clearInterval(mainCheckInterval);
                    if (paymentWindow && !paymentWindow.closed) {
                      paymentWindow.close();
                    }
                  }
                } catch (error) {
                  console.error('检查支付状态时出错:', error);
                }
              };
              
              // 主页面每3秒检查一次支付状态
              const mainCheckInterval = setInterval(checkMainPageStatus, 3000);
              
              // 60秒后停止检查
              setTimeout(() => {
                clearInterval(mainCheckInterval);
              }, 60000);
            }
          } else {
            console.error('未找到医生的挂号费信息');
            ElMessage.warning('获取挂号费信息失败，请联系客服');
          }
        } catch (error) {
          console.log('用户取消确认或发生错误:', error);
        }
      } else {
        console.log('未触发支付确认:', {
          isRegistrationSuccess,
          hasDoctor: !!registrationDoctor,
          doctorInfo: registrationDoctor
        });
      }
      return;
    }

    // 累积响应内容
    fullResponse += event.data;
    chatHistory.value[aiMessageIndex].content += event.data;
    scrollToBottom();
  }

  eventSource.onopen = () => {
    userInput.value = ''
  }

  eventSource.onerror = () => {
    eventSource.close()
    loading.value = false
    ElMessage.error('连接出错，请重试')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  }, 10)
}

// 切换聊天状态
const toggleChat = async () => {
  // 如果已经在实时咨询中，切换回AI对话
  if (wsState.value) {
    if (websocket.value) {
      websocket.value.close();
      wsState.value = false;
      isInConsultation.value = false;
      ElMessage.success('已切换回AI对话模式');
      // 更新输入框的占位符文本
      const inputEl = document.querySelector('.el-textarea__inner');
      if (inputEl) {
        inputEl.placeholder = '描述越细致，推荐越准确，至少2个字';
      }
    }
    return;
  }

  // 如果没有用户名，提示设置
  if (!userName.value) {
    ElMessage.warning('请先设置您的姓名');
    return;
  }

  // 尝试从聊天记录中获取最后一次对话的医生信息
  const lastDoctor = chatHistory.value
    .slice()
    .reverse()
    .find(msg => msg.role === 'assistant' && msg.doctorName);

  if (!lastDoctor?.doctorName) {
    ElMessage.warning('未找到最近的医生信息，请先进行预约');
    return;
  }

  try {
    // 连接到上一次对话的医生
    await connectToNetty({
      name: lastDoctor.doctorName,
      department: '专科'
    });
    
    // 更新输入框的占位符文本
    const inputEl = document.querySelector('.el-textarea__inner');
    if (inputEl) {
      inputEl.placeholder = '请输入要发送给医生的消息';
    }
    
    ElMessage.success(`已重新连接到${lastDoctor.doctorName}医生`);
  } catch (error) {
    console.error('重新连接失败:', error);
    ElMessage.error('连接失败，请重试');
  }
};

// 连接到Netty服务器
const connectToNetty = async (doctor) => {
  console.log('开始连接Netty服务器，医生信息：', doctor);
  console.log('当前用户名：', userName.value);

  // 检查必要信息
  if (!userName.value || !doctor?.name) {
    ElMessage.error('缺少必要的连接信息');
    console.error('连接失败：缺少用户名或医生名称');
    return;
  }

  // 如果已经有连接，先关闭
  if (websocket.value?.readyState === WebSocket.OPEN) {
    console.log('关闭现有WebSocket连接');
    websocket.value.close();
    await new Promise(resolve => setTimeout(resolve, 500));
  }

  try {
    console.log('创建新的WebSocket连接');
    websocket.value = new WebSocket(wsAddress.value);

    websocket.value.onopen = async () => {
      console.log('WebSocket连接已打开');
      wsState.value = true;

      try {
        // 发送患者信息
        const patientInfo = {
          code: "10001",
          nickname: userName.value, // 使用用户输入的名字
          role: "patient",
          target: doctor.name,
          department: doctor.department || '专科',
          type: "2"  // 添加type字段
        };

        console.log('发送患者信息:', patientInfo);
        websocket.value.send(JSON.stringify(patientInfo));

        // 等待500ms后发送加入群组信息
        await new Promise(resolve => setTimeout(resolve, 500));

        // 发送加入群组信息
        const groupInfo = {
          code: "10003",
          nickname: userName.value, // 使用用户输入的名字
          target: doctor.name
        };

        console.log('发送加入群组信息:', groupInfo);
        websocket.value.send(JSON.stringify(groupInfo));

        // 添加系统消息，记录医生信息
        chatHistory.value.push({
          role: 'assistant',
          content: `已成功连接到${doctor.name}医生的诊室`,
          doctorName: doctor.name
        });

        ElMessage.success('已成功连接到医生，现在可以开始实时对话');
        // 设置为实时咨询状态
        isInConsultation.value = true;
      } catch (error) {
        console.error('发送消息时出错:', error);
        ElMessage.error('连接出错，请重试');
        websocket.value?.close();
        isInConsultation.value = false;
      }
    };

    websocket.value.onmessage = (e) => {
      try {
        const data = JSON.parse(e.data);
        console.log('收到WebSocket消息:', data);

        if (data.code === '20001') {
          console.log('连接成功响应');
        } else if (data.code === '20003') {
          console.log('加入群组成功');
        }

        // 将消息添加到聊天记录，同时保存医生名称
        if (data.content || data.message) {
          const lastDoctorName = chatHistory.value.find(msg => msg.role === 'assistant')?.doctorName;
          chatHistory.value.push({
            role: data.nickname === userName.value ? 'user' : 'assistant',
            content: data.content || data.message,
            doctorName: data.nickname === userName.value ? undefined : (data.nickname || lastDoctorName)
          });
          scrollToBottom();
        }
      } catch (error) {
        console.error('处理WebSocket消息时出错:', error);
      }
    };

    websocket.value.onerror = (e) => {
      console.error('WebSocket错误:', e);
      wsState.value = false;
      isInConsultation.value = false;
      ElMessage.error('连接出错，请重试');
    };

    websocket.value.onclose = () => {
      console.log('WebSocket连接已关闭');
      wsState.value = false;
      isInConsultation.value = false;
      ElMessage.warning('与医生的连接已断开');
    };

  } catch (error) {
    console.error('连接Netty服务器失败:', error);
    ElMessage.error('连接服务器失败');
    wsState.value = false;
    isInConsultation.value = false;
  }
};

onMounted(() => {
  // 从 localStorage 获取保存的用户名
  const savedName = localStorage.getItem('patientName');
  if (savedName) {
    userName.value = savedName;
  }
  
  scrollToBottom();
  fetchDiseaseTags();
})
</script>

<style scoped lang="scss">
.ai-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 6px 10px;
    background: #4080ff;
    color: white;
    position: sticky;
    top: 0;
    z-index: 100;

    .title {
      font-size: 14px;
      font-weight: 500;
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .chat-btn {
      font-size: 16px;
      cursor: pointer;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 24px;

      .connection-status {
        position: absolute;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #ff4d4f;
        right: -2px;
        bottom: -2px;
        border: 2px solid #4080ff;

        &.connected {
          background: #52c41a;
        }
      }
    }

    .back, .notification {
      font-size: 16px;
      cursor: pointer;
    }
  }

  .chat-content {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    height: calc(100vh - 110px);
    position: relative;
    max-width: 900px;
    margin: 0 auto;
    width: 100%;

    .message {
      display: flex;
      align-items: flex-start;
      margin-bottom: 12px;

      .avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        overflow: hidden;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .message-content {
        max-width: 85%;
        margin: 0 8px;
        padding: 8px 12px;
        border-radius: 8px;
        font-size: 14px;
        line-height: 1.4;
      }
    }

    .doctor-message {
      .message-content {
        background: white;
        color: #333;
      }
    }

    .user-message {
      flex-direction: row-reverse;

      .message-content {
        background: #4080ff;
        color: white;
      }
    }

    .quick-tags {
      margin: 12px auto;
      max-width: 900px;

      .hint-text {
        color: #666;
        font-size: 13px;
        margin-bottom: 8px;
      }

      .tags-container {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .tag-item {
          cursor: pointer;
          padding: 4px 12px;
          border-radius: 16px;
          font-size: 13px;
          line-height: 1.4;
          background: white;
          color: #4080ff;
          border: 1px solid #4080ff;

          &:hover {
            background: #4080ff;
            color: white;
          }
        }
      }
    }
  }

  .input-area {
    padding: 12px 16px;
    max-width: 900px;
    margin: 0 auto;
    width: 100%;
    border-top: 1px solid #eee;
    display: flex;
    align-items: center;
    gap: 10px;
    position: sticky;
    bottom: 0;
    z-index: 100;
    background: white;
    height: 70px;

    .input-box {
      flex: 1;
      position: relative;

      :deep(.el-textarea__inner) {
        padding: 8px 50px 8px 12px;
        resize: none;
        border-radius: 16px;
        min-height: 46px;
        max-height: 46px;
        line-height: 20px;
        font-size: 14px;
      }

      .action-buttons {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        display: flex;
        gap: 12px;

        .action-icon {
          font-size: 18px;
          color: #999;
          cursor: pointer;

          &:hover {
            color: #4080ff;
          }
        }
      }
    }

    .send-btn {
      border-radius: 16px;
      height: 46px;
      padding: 0 20px;
      font-size: 14px;
      min-width: 60px;
    }
  }
}

:deep(.el-timeline-item__node) {
  display: none;
}

:deep(.el-timeline-item__tail) {
  display: none;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 0;
}

.doctors-list {
  margin-top: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  
  .list-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 12px;
    font-weight: 500;
  }

  .doctor-card {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;
    border: 1px solid #eee;
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    &:hover {
      border-color: #4080ff;
      box-shadow: 0 2px 8px rgba(64, 128, 255, 0.1);
    }

    .doctor-info {
      padding: 16px;

      .doctor-main {
        display: flex;
        gap: 12px;
        margin-bottom: 12px;

        .doctor-avatar {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          overflow: hidden;
          flex-shrink: 0;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .doctor-details {
          flex: 1;

          .doctor-name {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
          }

          .doctor-specialty {
            font-size: 13px;
            color: #666;
            line-height: 1.5;
          }
        }
      }

      .doctor-price {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px solid #f0f0f0;

        .price-info {
          display: flex;
          align-items: baseline;
          gap: 4px;

          .price-label {
            font-size: 13px;
            color: #666;
          }

          .price-amount {
            font-size: 18px;
            font-weight: 600;
            color: #f56c6c;
          }
        }

        .consult-btn {
          font-size: 14px;
          padding: 8px 20px;
          border-radius: 20px;
        }
      }
    }
  }
}
</style>
